package com.blue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blue.entity.Line;
import com.blue.entity.LineStation;
import com.blue.entity.Station;
import com.blue.mapper.LineMapper;
import com.blue.mapper.LineStationMapper;
import com.blue.mapper.StationMapper;
import com.blue.service.LineService;
import com.blue.service.LineStationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author blue
 * @since 2024-11-25
 */
@Service
public class LineStationServiceImpl extends ServiceImpl<LineStationMapper, LineStation> implements LineStationService {
    @Autowired
    LineService lineService;
    @Autowired
    LineMapper lineMapper;
    @Autowired
    StationMapper stationMapper;
    @Autowired
    LineStationMapper lineStationMapper;

    @Override
    public int mapping(String lineName, String... stationNames) {
        // 1. 查询线路ID

        Line line = lineService.findLineByName(lineName);
        Integer lineId = line.getLineId();
        // 2. 查询站点ID并依序排列

        QueryWrapper<Station> stationQueryWrapper = new QueryWrapper<>();
        stationQueryWrapper.in("station_name",stationNames);
        List<Station> stations = stationMapper.selectList(stationQueryWrapper);

        // 将站点名称和查询到的站点对象映射，以便快速查找
        Map<String, Integer> stationIdMap = stations.stream()
                .collect(Collectors.toMap(Station::getStationName, Station::getStationId));

        // 3. 插入站点关联
        for (int i = 0; i < stationNames.length; i++) {
            int stationId = stationIdMap.get(stationNames[i]);
            LineStation lineStation = new LineStation();
            lineStation.setLineId(lineId);
            lineStation.setStationId(stationId);
            lineStation.setPrevId(i > 0 ? stationIdMap.get(stationNames[i - 1]) : 0);
            lineStation.setNextId(i < stationNames.length - 1 ? stationIdMap.get(stationNames[i + 1]) : 0);
            lineStationMapper.insert(lineStation);
        }

        return stationNames.length; // 返回插入的站点数量

    }
}
